package com.yy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yy.config.ApiConfig;
import com.yy.domain.*;
import com.yy.dao.SecondHospitalAppointmentsMapper;
import com.yy.dto.ContentDTO;
import com.yy.dto.SureAppointmentDTO;
import com.yy.dto.mother.*;
import com.yy.enums.TaskStatus;
import com.yy.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.utils.ConvertUtils;
import com.yy.utils.HutoolUtil;
import com.yy.utils.ImageUtils;
import com.yy.utils.SecretUtil;
import com.yy.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 姚欣宏
 * @since 2023-10-24
 */
@Slf4j
@Service
public class SecondHospitalAppointmentsServiceImpl extends ServiceImpl<SecondHospitalAppointmentsMapper, SecondHospitalAppointmentsDO> implements SecondHospitalAppointmentsService {

    private final MotherChildrenService motherChildrenService;
    private final SecondHospitalApiLogService apiLogService;
    private final ApiConfig apiConfig;
    private final SecondHospitalImageDataService imageDataService;


    public SecondHospitalAppointmentsServiceImpl(MotherChildrenService motherChildrenService, SecondHospitalApiLogService apiLogService, ApiConfig apiConfig, SecondHospitalImageDataService imageDataService) {
        this.motherChildrenService = motherChildrenService;
        this.apiLogService = apiLogService;
        this.apiConfig = apiConfig;
        this.imageDataService = imageDataService;
    }

    private String getUrlByName(String name) {
        return apiConfig.getEndpoints().stream()
                .filter(endpoint -> endpoint.getName().equals(name))
                .findFirst()
                .map(ApiConfig.Endpoint::getUrl)
                .orElseThrow(() -> new RuntimeException("No endpoint found with name: " + name));
    }

    private static final String ORGAN_CODE = "HXD2";
    private static final String APP_CODE = "HXFYAPP";
    private static final String CHANNEL_CODE = "PATIENT_WECHAT_APPLET";
    private static final String LOGIN_DEVICE_NUM = "236511321231441";
    private static final String LOGIN_DEVICE_TYPE = "WX_APP";
    private static final String OPEN_ID = "odLSW5bJttmuRFr_AUxOKEexcXuM";
    private static final String WECHAT_REQUEST_TYPE = "MINI_PROGRAM";
    private static final String NO_APPOINTMENT_STATUS = "无号";

    @Value("${secondsValue}")
    private Integer SECONDS;
    private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

    /**
     * @param phoneNum
     * @return
     */
    @Override
    public AuthDataDTO getAuthCode(String phoneNum) {
        return motherChildrenService.getAuthCode(phoneNum);
    }

    /**
     * @param appointmentTasksVO
     * @return
     */
    @Override
    public Integer tasksCreate(AppointmentTasksVO appointmentTasksVO) {
        WeChatLoginVO weChatLoginVO = new WeChatLoginVO();
        weChatLoginVO.setOrganCode(ORGAN_CODE);
        weChatLoginVO.setAppCode(APP_CODE);
        weChatLoginVO.setChannelCode(CHANNEL_CODE);
        weChatLoginVO.setAuthKey(appointmentTasksVO.getAuthKey());
        weChatLoginVO.setAccountNo(appointmentTasksVO.getAppointmentPhone());
        weChatLoginVO.setAuthCode(appointmentTasksVO.getAuthCode());
        weChatLoginVO.setLoginDeviceNum(LOGIN_DEVICE_NUM);
        weChatLoginVO.setLoginDeviceType(LOGIN_DEVICE_TYPE);
        weChatLoginVO.setOpenId(OPEN_ID);
        weChatLoginVO.setWeChatRequestType(WECHAT_REQUEST_TYPE);
        LoginResponseDataDTO loginResponseDataDTO = motherChildrenService.login(weChatLoginVO);
        String token = loginResponseDataDTO.getToken();
        if (StringUtils.isNoneBlank(token)) {
            SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = ConvertUtils.beanCopy(appointmentTasksVO, SecondHospitalAppointmentsDO.class);
            secondHospitalAppointmentsDO.setToken(token);
            secondHospitalAppointmentsDO.setCreateTime(new Date());
            secondHospitalAppointmentsDO.setTaskStatus(TaskStatus.PENDING_CONFIGURATION.getCode());
            secondHospitalAppointmentsDO.setStatus(null);
            secondHospitalAppointmentsDO.setHospitalCode(ORGAN_CODE);
            save(secondHospitalAppointmentsDO);
            Integer id = secondHospitalAppointmentsDO.getId();
            addApiLog(id, "附二院-微信小程序登录", getUrlByName("login"), loginResponseDataDTO.toString());
            return id;
        }
        return null;
    }

    /**
     * @param appointmentTasksPageVO
     * @return
     */
    @Override
    public PageInfo<SecondHospitalAppointmentsDO> tasksList(AppointmentTasksPageVO appointmentTasksPageVO) {
        PageHelper.startPage(appointmentTasksPageVO.getPageNum(), appointmentTasksPageVO.getPageSize());
        QueryWrapper<SecondHospitalAppointmentsDO> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(appointmentTasksPageVO.getHospitalCode()), "hospital_code", appointmentTasksPageVO.getHospitalCode())
                .eq(StringUtils.isNotBlank(appointmentTasksPageVO.getAppointmentDate()), "appointment_date", appointmentTasksPageVO.getAppointmentDate())
                .eq(StringUtils.isNotBlank(appointmentTasksPageVO.getServer()), "server", appointmentTasksPageVO.getServer())
                .like(StringUtils.isNotBlank(appointmentTasksPageVO.getAppointmentPhone()), "appointment_phone", appointmentTasksPageVO.getAppointmentPhone())
                .like(StringUtils.isNotBlank(appointmentTasksPageVO.getDoctor()), "doc_name", appointmentTasksPageVO.getDoctor())
                .like(StringUtils.isNotBlank(appointmentTasksPageVO.getProcessor()), "processor", appointmentTasksPageVO.getProcessor())
                .orderByDesc("id");
        List<SecondHospitalAppointmentsDO> secondHospitalAppointmentsDOS = list(wrapper);
        PageInfo<SecondHospitalAppointmentsDO> pageInfo = new PageInfo(secondHospitalAppointmentsDOS);
        return pageInfo;
    }

    /**
     * @param cardRequestVO
     * @return
     */
    @Override
    public List<UserOrganCardDetailDTO> getUserOrganCardList(CardRequestVO cardRequestVO) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(cardRequestVO.getId());
        cardRequestVO.setToken(secondHospitalAppointmentsDO.getToken());
        cardRequestVO.setOrganCode(ORGAN_CODE);
        cardRequestVO.setAppCode(APP_CODE);
        cardRequestVO.setChannelCode(CHANNEL_CODE);
        return motherChildrenService.getUserOrganCardList(cardRequestVO);
    }

    /**
     * @param treeRequestVO
     * @return
     */
    @Override
    public DepartmentInfoDTO selTree(TreeRequestVO treeRequestVO) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(treeRequestVO.getId());
        treeRequestVO.setToken(secondHospitalAppointmentsDO.getToken());
        treeRequestVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
        treeRequestVO.setAppCode(APP_CODE);
        treeRequestVO.setChannelCode(CHANNEL_CODE);
        treeRequestVO.setSelectionTypeId("dept");
        return motherChildrenService.selTree(treeRequestVO);
    }

    /**
     * @param treeRequestVO
     * @return
     */
    @Override
    public DetailedDataResponseDTO selDocListSelectionPage(TreeRequestVO treeRequestVO) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(treeRequestVO.getId());
        treeRequestVO.setToken(secondHospitalAppointmentsDO.getToken());
        treeRequestVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
        treeRequestVO.setAppCode(APP_CODE);
        treeRequestVO.setChannelCode(CHANNEL_CODE);
        treeRequestVO.setIsHaveNo(false);
        treeRequestVO.setKeyWordType("doctorName");
        treeRequestVO.setChannel("MOBILE");
        return motherChildrenService.selDocListSelectionPage(treeRequestVO);
    }

    /**
     * @param doctorRequestVO
     * @return
     */
    @Override
    public PageDoctorResponseDTO selDoctorListPaging(DoctorRequestVO doctorRequestVO) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(doctorRequestVO.getId());
        doctorRequestVO.setToken(secondHospitalAppointmentsDO.getToken());
        doctorRequestVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
        doctorRequestVO.setAppCode(APP_CODE);
        doctorRequestVO.setChannelCode(CHANNEL_CODE);
        doctorRequestVO.setChannel("MOBILE");
        return motherChildrenService.selDoctorListPaging(doctorRequestVO);
    }

    /**
     * @param doctorInfoRequestVO
     * @return
     */
    @Override
    public DataResponseDTO selDoctorSchedule(DoctorInfoRequestVO doctorInfoRequestVO) {
        // 根据医生的ID获取SecondHospitalAppointmentsDO对象
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(doctorInfoRequestVO.getId());
        // 将必要信息设置到doctorInfoRequestVO中
        doctorInfoRequestVO.setToken(secondHospitalAppointmentsDO.getToken());
        doctorInfoRequestVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
        doctorInfoRequestVO.setAppCode(APP_CODE);
        doctorInfoRequestVO.setChannelCode(CHANNEL_CODE);
        // 调用服务获取医生的排班信息
        DataResponseDTO dataResponseDTO = motherChildrenService.selDoctorSchedule(doctorInfoRequestVO);
        ScheduleRespVo scheduleRespVo = dataResponseDTO.getScheduleRespVo();
        List<ScheduleDTO> schedules = scheduleRespVo.getScheduleRespVos();
        // 准备日期和时间进行比较
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        String formattedAppointmentDate = sdf.format(secondHospitalAppointmentsDO.getTreatmentDate());
        String appointmentTimeRange = secondHospitalAppointmentsDO.getTreatmentRange() == 0 ? "上午" : "下午";
        // 标记是否找到了匹配的排班
        boolean isMatchedSchedule = false;
        // 标记是否更新了计划
        boolean isUpdated = false;
        // 遍历排班信息
        for (ScheduleDTO currentSchedule : schedules) {
            if (formattedAppointmentDate.equals(currentSchedule.getScheduleDate()) && appointmentTimeRange.equals(currentSchedule.getTimeRange())) {
                isMatchedSchedule = true;
                // 如果当前排班有可预约的号
                if (!NO_APPOINTMENT_STATUS.equals(currentSchedule.getStatusName())) {
                    secondHospitalAppointmentsDO.setTaskStatus(TaskStatus.PENDING_INITIATION.getCode());
                    secondHospitalAppointmentsDO.setSysScheduleId(currentSchedule.getSysScheduleId());
                    isUpdated = true;
                }
                break; // 找到匹配的排班信息后不需要继续遍历
            }
        }
        // 如果没有找到匹配的排班信息或者排班信息中没有可预约的号，则认为排班失败
        if (!isMatchedSchedule || !isUpdated) {
            secondHospitalAppointmentsDO.setTaskStatus(TaskStatus.RETRIEVAL_FAILED.getCode());
        }
        updateById(secondHospitalAppointmentsDO);
        // 记录API调用日志
        addApiLog(secondHospitalAppointmentsDO.getId(), "附二院-获取排班", getUrlByName("doctorSchedule"), dataResponseDTO.toString());
        return dataResponseDTO;
    }


    /**
     * @param appointmentTasksVO
     * @return
     */
    @Override
    public Integer taskConfiguration(AppointmentTasksVO appointmentTasksVO) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(appointmentTasksVO.getId());
        BeanUtil.copyProperties(appointmentTasksVO, secondHospitalAppointmentsDO);
        try {
            secondHospitalAppointmentsDO.setAppointmentDate(DATE_FORMAT.get().parse(appointmentTasksVO.getAppointmentDate()));
            secondHospitalAppointmentsDO.setTreatmentDate(DATE_FORMAT.get().parse(appointmentTasksVO.getTreatmentDate()));
        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid date format provided.", e);
        }
        secondHospitalAppointmentsDO.setTaskStatus(TaskStatus.PENDING_SCHEDULE_RETRIEVAL.getCode());
        secondHospitalAppointmentsDO.setUpdateTime(new Date());
        updateById(secondHospitalAppointmentsDO);
        return secondHospitalAppointmentsDO.getId();
    }

    /**
     * @param scheduleInfoRequestVO
     * @return
     */
    @Override
    public DoctorDetailDTO selSureOrderPage(ScheduleInfoRequestVO scheduleInfoRequestVO) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(scheduleInfoRequestVO.getId());
        scheduleInfoRequestVO.setToken(secondHospitalAppointmentsDO.getToken());
        scheduleInfoRequestVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
        scheduleInfoRequestVO.setAppCode(APP_CODE);
        scheduleInfoRequestVO.setSysScheduleId(secondHospitalAppointmentsDO.getSysScheduleId());
        return motherChildrenService.selSureOrderPage(scheduleInfoRequestVO);
    }

    /**
     * @param appointmentRequestVO
     * @return
     */
    @Override
    public AppointmentResponseDTO orderCheck(AppointmentRequestVO appointmentRequestVO) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(appointmentRequestVO.getId());
        appointmentRequestVO.setToken(secondHospitalAppointmentsDO.getToken());
        appointmentRequestVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
        appointmentRequestVO.setAppCode(APP_CODE);
        appointmentRequestVO.setChannelCode(CHANNEL_CODE);
        appointmentRequestVO.setScheduleId(secondHospitalAppointmentsDO.getSysScheduleId());
        appointmentRequestVO.setCardId(secondHospitalAppointmentsDO.getCardId());
        return motherChildrenService.orderCheck(appointmentRequestVO);
    }

    /**
     * @param imageRequestVO
     * @return
     */
    @Override
    public ImageCodeDTO getImageCode(ImageRequestVO imageRequestVO) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(imageRequestVO.getId());
        imageRequestVO.setToken(secondHospitalAppointmentsDO.getToken());
        imageRequestVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
        imageRequestVO.setAppCode(APP_CODE);
        imageRequestVO.setChannelCode(CHANNEL_CODE);
        imageRequestVO.setType("WECHAT");
        ImageCodeDTO imageDTO = motherChildrenService.getImageCode(imageRequestVO);
        if (!Objects.isNull(imageDTO)) {
            addApiLog(secondHospitalAppointmentsDO.getId(), "附二院-获取验证码", getUrlByName("imageCode"), imageDTO.toString());
            String code = ImageUtils.recognition(imageDTO.getImageData());
            imageDTO.setImageCode(code);
            SecondHospitalImageDataDO imageDataDO = ConvertUtils.beanCopy(imageDTO, SecondHospitalImageDataDO.class);
            imageDataDO.setCreateTime(new Date());
            imageDataDO.setImageCode(code);
            imageDataDO.setTaskId(secondHospitalAppointmentsDO.getId());
            imageDataDO.setIsUsed(0);
            imageDataService.save(imageDataDO);
        }
        return imageDTO;
    }

    /**
     * @param informationVO
     * @return
     */
    @Override
    public DetailResponseDTO sureOrder(InformationVO informationVO) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(informationVO.getId());
        QueryWrapper<SecondHospitalImageDataDO> wrapper = new QueryWrapper<>();
        Integer taskId = informationVO.getId();
        wrapper.eq("task_id", taskId);
        wrapper.eq("is_used", 0);
        wrapper.orderByDesc("id");
        List<SecondHospitalImageDataDO> imageDataDOS = imageDataService.list(wrapper);
        log.info("附二院提交预约-手动:" + taskId);
        if (CollUtil.isNotEmpty(imageDataDOS)) {
            SecondHospitalImageDataDO imageDataDO = imageDataDOS.stream().findAny().get();
            imageDataDO.setIsUsed(1);
            imageDataService.updateById(imageDataDO);
            informationVO.setToken(secondHospitalAppointmentsDO.getToken());
            informationVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
            informationVO.setAppCode(APP_CODE);
            informationVO.setChannelCode(CHANNEL_CODE);
            informationVO.setCardId(secondHospitalAppointmentsDO.getCardId());
            informationVO.setScheduleId(secondHospitalAppointmentsDO.getSysScheduleId());
            informationVO.setSureOrderVerify("identifyingCode");
            informationVO.setSureOrderVerifyInfo(imageDataDO.getImageCode());
            informationVO.setSureOrderVerifyIndex(imageDataDO.getBizSeq());
            informationVO.setVerifyImageCodeType("WECHAT");
            DetailResponseDTO detailResponseDTO = motherChildrenService.sureOrder(informationVO);
            addApiLog(secondHospitalAppointmentsDO.getId(), "附二院-提交订单-手动", getUrlByName("sureOrder"), detailResponseDTO.toString());
            if (StringUtils.isNotBlank(detailResponseDTO.getAppointmentId())) {
                secondHospitalAppointmentsDO.setAppointmentId(detailResponseDTO.getAppointmentId());
                secondHospitalAppointmentsDO.setTaskStatus(TaskStatus.APPOINTMENT_SUCCESSFUL.getCode());
            } else {
                secondHospitalAppointmentsDO.setTaskStatus(TaskStatus.APPOINTMENT_FAILED.getCode());
            }
            secondHospitalAppointmentsDO.setUpdateTime(new Date());
            updateById(secondHospitalAppointmentsDO);
            return detailResponseDTO;
        } else {
            return null;
        }

    }

    /**
     * @param queryCriteriaVO
     * @return
     */
    @Override
    public PatientPageInfoDTO recordPage(QueryCriteriaVO queryCriteriaVO) {
        // 获取预约信息
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(queryCriteriaVO.getId());
        // 设置查询条件
        queryCriteriaVO.setToken(secondHospitalAppointmentsDO.getToken());
        queryCriteriaVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
        queryCriteriaVO.setAppCode(APP_CODE);
        queryCriteriaVO.setChannelCode(CHANNEL_CODE);
        queryCriteriaVO.setAsc(false);
        // 执行查询
        PatientPageInfoDTO patientPageInfoDTO = motherChildrenService.recordPage(queryCriteriaVO);
        List<PatientInfoDTO> patientInfoDTOS = patientPageInfoDTO.getContent();
        // 检查并更新匹配的记录
        if (CollUtil.isNotEmpty(patientInfoDTOS)) {
            for (PatientInfoDTO patientInfoDTO : patientInfoDTOS) {
                // 格式化日期以匹配查询条件
                String formattedTreatmentDate = new SimpleDateFormat("yyyy-MM-dd").format(secondHospitalAppointmentsDO.getTreatmentDate());
                // 转换时间范围为字符串描述
                String treatmentRangeDescription = secondHospitalAppointmentsDO.getTreatmentRange() == 0 ? "上午" : "下午";
                // 检查匹配条件
                if (patientInfoDTO.getDoctorId().equals(secondHospitalAppointmentsDO.getDoctorId())
                        && patientInfoDTO.getAdmDate().equals(formattedTreatmentDate)
                        && patientInfoDTO.getAdmTimeRangeDescription().equals(treatmentRangeDescription)) {
                    // 更新任务状态和更新时间
                    secondHospitalAppointmentsDO.setTaskStatus(TaskStatus.APPOINTMENT_SUCCESSFUL.getCode());
                    secondHospitalAppointmentsDO.setUpdateTime(new Date());
                    updateById(secondHospitalAppointmentsDO);
                    break; // 匹配后跳出循环，假设每次查询只处理一个匹配项
                }
            }
        }
        return patientPageInfoDTO;
    }


    /**
     * @param cancelVO
     */
    @Override
    public void cancel(CancelVO cancelVO) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(cancelVO.getId());
        cancelVO.setToken(secondHospitalAppointmentsDO.getToken());
        cancelVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
        cancelVO.setAppCode(APP_CODE);
        cancelVO.setChannelCode(CHANNEL_CODE);
        cancelVO.setCancelType("4");
        motherChildrenService.cancel(cancelVO);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public String checkToken(Integer id) {
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = getById(id);
        CardRequestVO cardRequestVO = new CardRequestVO();
        cardRequestVO.setToken(secondHospitalAppointmentsDO.getToken());
        cardRequestVO.setOrganCode(ORGAN_CODE);
        cardRequestVO.setAppCode(APP_CODE);
        cardRequestVO.setChannelCode(CHANNEL_CODE);
        motherChildrenService.getUserOrganCardList(cardRequestVO);
        return "Token 有效";
    }

    /**
     * @param id
     */
    @Override
    public void copy(Integer id) {
        SecondHospitalAppointmentsDO appointmentTasksDO = getById(id);
        SecondHospitalAppointmentsDO secondHospitalAppointmentsDO = new SecondHospitalAppointmentsDO();
        secondHospitalAppointmentsDO.setAppointmentPerson(appointmentTasksDO.getAppointmentPerson());
        secondHospitalAppointmentsDO.setCustomer(appointmentTasksDO.getCustomer());
        secondHospitalAppointmentsDO.setProcessor(appointmentTasksDO.getProcessor());
        secondHospitalAppointmentsDO.setAppointmentPhone(appointmentTasksDO.getAppointmentPhone());
        secondHospitalAppointmentsDO.setToken(appointmentTasksDO.getToken());
        secondHospitalAppointmentsDO.setCreateTime(new Date());
        secondHospitalAppointmentsDO.setTaskStatus(TaskStatus.PENDING_CONFIGURATION.getCode());
        secondHospitalAppointmentsDO.setStatus(null);
        secondHospitalAppointmentsDO.setHospitalCode(ORGAN_CODE);
        save(secondHospitalAppointmentsDO);
    }

    /**
     * @param secondHospitalAppointmentsDO
     */
    @Override
    public void autoSureAppointment(SecondHospitalAppointmentsDO secondHospitalAppointmentsDO) {
        log.info("开始自动提交" + secondHospitalAppointmentsDO.getDocName());
        if (secondHospitalAppointmentsDO.getTaskStatus().equals(TaskStatus.PENDING_INITIATION.getCode())) {
            QueryWrapper<SecondHospitalImageDataDO> wrapper = new QueryWrapper<>();
            wrapper.eq("task_id", secondHospitalAppointmentsDO.getId());
            wrapper.eq("is_used", 0);
            List<SecondHospitalImageDataDO> imageDataDOS = imageDataService.list(wrapper);
            if (CollUtil.isNotEmpty(imageDataDOS)) {
                for (SecondHospitalImageDataDO imageDataDO : imageDataDOS) {
                    subscribe(secondHospitalAppointmentsDO, imageDataDO);
                    try {
                        Thread.sleep(SECONDS); // 0.5秒钟，单位为毫秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void subscribe(SecondHospitalAppointmentsDO secondHospitalAppointmentsDO, SecondHospitalImageDataDO imageDataDO) {
        log.info("开始自动提交验证码" + secondHospitalAppointmentsDO.getDocName() + imageDataDO.getId());
        imageDataDO.setIsUsed(1);
        imageDataService.updateById(imageDataDO);
        secondHospitalAppointmentsDO.setTaskStatus(TaskStatus.APPOINTMENT_FAILED.getCode());
        secondHospitalAppointmentsDO.setUpdateTime(new Date());
        updateById(secondHospitalAppointmentsDO);
        InformationVO informationVO = new InformationVO();
        informationVO.setToken(secondHospitalAppointmentsDO.getToken());
        informationVO.setOrganCode(secondHospitalAppointmentsDO.getHospitalCode());
        informationVO.setAppCode(APP_CODE);
        informationVO.setChannelCode(CHANNEL_CODE);
        informationVO.setCardId(secondHospitalAppointmentsDO.getCardId());
        informationVO.setScheduleId(secondHospitalAppointmentsDO.getSysScheduleId());
        informationVO.setSureOrderVerify("identifyingCode");
        informationVO.setSureOrderVerifyInfo(imageDataDO.getImageCode());
        informationVO.setSureOrderVerifyIndex(imageDataDO.getBizSeq());
        informationVO.setVerifyImageCodeType("WECHAT");
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(() -> {
            try {
                DetailResponseDTO detailResponseDTO = motherChildrenService.sureOrder(informationVO);
                // 处理返回结果
                addApiLog(secondHospitalAppointmentsDO.getId(), "附二院-提交订单-自动", getUrlByName("sureOrder"), detailResponseDTO.toString());
            } catch (Exception e) {
                // 处理异常
                addApiLog(secondHospitalAppointmentsDO.getId(), "附二院-提交订单-自动", getUrlByName("sureOrder"), e.getMessage());
                log.info("发生异常：" + e.getMessage());
            }
        });
        executorService.shutdown();
    }

    private SecondHospitalApiLogDO addApiLog(Integer id, String name, String url, String json) {
        SecondHospitalApiLogDO apiLogDO = new SecondHospitalApiLogDO();
        apiLogDO.setTaskId(id);
        apiLogDO.setName(name);
        apiLogDO.setUrl(url);
        apiLogDO.setRequestParams(json);
        apiLogDO.setCreateTime(new Date());
        apiLogService.save(apiLogDO);
        return apiLogDO;
    }
}
